package ch2.tools;


import tools.SleepTools;

import java.util.concurrent.CountDownLatch;

/**
 * 类说明：演示CountDownLatch用法，
 * 共5个初始化子线程和一个主线程，6个闭锁扣除点，扣除完毕后，主线程和业务线程才能继续执行
 */
public class UseCountDownLatch {
    //六个闭锁扣除点
    private static CountDownLatch latch = new CountDownLatch(6);

    /*初始化线程*/
    private static class InitThread implements Runnable {
        @Override
        public void run() {
            System.out.println("初始化线程Thread_" + Thread.currentThread().getId() + " ready init work......");
            latch.countDown();
            for (int i = 0; i < 2; i++) {
                System.out.println("初始化线程Thread_" + Thread.currentThread().getId() + " ........continue do its work");
            }
        }
    }

    /*业务线程等待latch的计数器为0完成*/
    private static class BusiThread implements Runnable {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println("业务线程BusiThread_" + Thread.currentThread().getId() + " do business-----");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        //启动四个初始化线程，减四次
        for (int i = 0; i <= 3; i++) {
            Thread thread = new Thread(new InitThread());
            thread.start();
        }

        //启动一个新线程,减两次
        new Thread(new Runnable() {
            public void run() {
                SleepTools.ms(1);
                System.out.println("新线程Thread_" + Thread.currentThread().getId() + " ready init work step 1st......");
                latch.countDown();
                System.out.println("新线程begin step 2nd.......");
                SleepTools.ms(1);
                System.out.println("新线程Thread_" + Thread.currentThread().getId() + " ready init work step 2nd......");
                latch.countDown();
            }
        }).start();


        //启动一个业务线程  这个业务线程要等latch为0才会启动
        new Thread(new BusiThread()).start();


        //主线程要等latch为0才会启动
        latch.await();
        System.out.println("Main do ites work........");
    }
}
